package club.adger.server.service.impl;

import club.adger.server.dto.ChapterDto;
import club.adger.server.dto.ChapterPageDto;
import club.adger.server.entity.Chapter;
import club.adger.server.entity.ChapterExample;
import club.adger.server.mapper.ChapterMapper;
import club.adger.server.service.ChapterService;
import club.adger.server.utils.CopyUtil;
import club.adger.server.utils.UuidUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: Adger
 * @Date: 2020/07/25/5:23
 */
@Service
public class ChapterServiceImpl implements ChapterService {
    @Resource
    private ChapterMapper chapterMapper;

    /**
     * PageDto 是分页数据传输的 实体类对象
     * @param chapterPageDto
     * @return
     */
    public void list(ChapterPageDto chapterPageDto){
        PageHelper.startPage(chapterPageDto.getPage(),chapterPageDto.getSize());
        ChapterExample chapterExample = new ChapterExample();
        ChapterExample.Criteria criteria = chapterExample.createCriteria();
        if(!StringUtils.isEmpty(chapterPageDto.getCourseId())){
            criteria.andCourseIdEqualTo(chapterPageDto.getCourseId());
        }

        List<Chapter> chaptersList = chapterMapper.selectByExample(chapterExample);

        PageInfo<Chapter> chapterPageInfo = new PageInfo<>(chaptersList);
        chapterPageDto.setTotal(chapterPageInfo.getTotal());
        List<ChapterDto> chapterDtoList = CopyUtil.copyList(chaptersList, ChapterDto.class);
        chapterPageDto.setList(chapterDtoList);
    }

    /**
     * 这是新增或者修改的方法 下面 private 这里是公开的方法 调用就这个方法 不管内部怎么实现的
     * @param chapterDto
     */
    public void add(ChapterDto chapterDto){
        Chapter chapter = CopyUtil.copy(chapterDto, Chapter.class);
        if(StringUtils.isEmpty(chapterDto.getId())){
            this.insert(chapter);
        }else{
            this.update(chapter);
        }
    }

    /**
     * 这里都是private
     * 这是添加的方法
     * @param chapter
     */
    private void insert(Chapter chapter){
        chapter.setId(UuidUtil.getShortUuid());
        chapterMapper.insert(chapter);
    }

    /**
     * 这里也是private 这是修改的方法
     * @param chapter
     */
    private void update(Chapter chapter){
        chapterMapper.updateByPrimaryKey(chapter);
    }

    /**
     * 删除
     * @param id
     */
    @Override
    public void delete(String id) {
        chapterMapper.deleteByPrimaryKey(id);
    }
}
